package no.awi.wpd.serialize.impl;

import java.io.Reader;
import java.io.Writer;

import no.awi.wpd.combat.model.Combat;
import no.awi.wpd.probability.ProbabilityDistribution;
import no.awi.wpd.serialize.SerializeService;
import no.awi.wpd.unit.model.Unit;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;

// TODO - rename to SerializeServiceXStreamImpl
public class XmlServiceImpl implements SerializeService {

	private XStream xstream;
	private XStream jsonXStream;

    public void serialize(Combat combat, Writer writer) {
		getXStream().toXML(combat, writer);
	}

	public Combat deserializeCombat(Reader reader) {
		return (Combat) getXStream().fromXML(reader);
	}
	
	public void serialize(ProbabilityDistribution probabilityDistribution, Writer writer) {
		getJsonXStream().toXML(probabilityDistribution, writer);
	}
	
	private XStream getXStream() {
	    if (xstream == null) {
    	    xstream = new XStream();
    	    xstream.addImplicitCollection(Combat.class, "chargers", "charger", Unit.class);
    	    xstream.alias("combat", Combat.class);
    	    xstream.useAttributeFor(int.class);
    	    xstream.useAttributeFor(String.class);
	    }
	    return xstream;
	}

	private XStream getJsonXStream() {
		if (jsonXStream == null) {
			jsonXStream = new XStream(new JsonHierarchicalStreamDriver());
			jsonXStream.addImplicitCollection(Combat.class, "chargers", "charger", Unit.class);
			jsonXStream.alias("combat", Combat.class);
			jsonXStream.useAttributeFor(int.class);
			jsonXStream.useAttributeFor(String.class);
		}
		return jsonXStream;
	}
	
}
